<template>
  <el-dialog v-model="dialogEndable" :title="dialogTitle">
    <el-form>
      <el-form-item label="公告标题">
        <el-input v-model="mod.title"></el-input>
      </el-form-item>
      <el-form-item label="公告正文">
        <el-input v-if="!isPreview" v-model="mod.content" type="textarea" autosize />
        <div v-else v-html="depDetail" class="project-dialog-detail"></div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="switchPrevie">
          {{ isPreview ? '编辑' : '预览' }}
        </el-button>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="formSubmit">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { post } from '../utils/common/api'
import MarkdownIt from 'markdown-it'

export default {
  data() {
    return {
      id: undefined,

      dialogEndable: false,

      dialogTitle: '',

      isPreview: false,

      mod: {
        title: '',
        content: '',
      }

    }
  },

  computed: {
    depDetail() {
      const md = new MarkdownIt()
      const result = md.render(this.mod.content)
      return result
    }
  },

  methods: {
    openDialog() {
      this.dialogEndable = true
    },

    closeDialog() {
      this.dialogEndable = false
    },

    setDetail(id, notice) {
      this.id = id
      this.mod.title = notice.title
      this.mod.content = notice.content
      this.dialogTitle = `更新公告信息 No.${id}`
    },

    async formSubmit() {
      const res = await post('/info/notice/update', {
        id: this.id,
        mod: this.mod
      });
      this.$emit('update');

      ElNotification({
        title: '修改成功',
        message: `您刚刚更新了公告(${res.id})的信息`,
        type: 'success',
        position: 'bottom-right',
      });

      this.closeDialog();
      this.isPreview = false;

    },

    switchPrevie() {
      this.isPreview = !this.isPreview
    }
  }
}
</script>

<style scoped>
.project-dialog-detail {
  width: 100%;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 12px;
  text-align: left;
  font-size: 15px;
}
</style>
